﻿/**
Author : Arthur Rayer
Date : 05/11/2011

Description:
	Function in charge of the instanciation of MainTower at the very beginning of the game.
	It first tries to set the location based on a LocalSearch for church.  
	If there is no church close to the focused position, it searchs for a nearby streeview location.  
	If it fails, the MainTower location will be associated with the map center.
**/

HSEngine.prototype.executeLocalSearch = function(baseKey){
	this.localSearch.setSearchCompleteCallback(this, function(){
		//Process results
		if (this.localSearch.results && 
			this.localSearch.results.length > 0 && 
			this.map.getCenter().distanceFrom(new GLatLng(this.localSearch.results[0].lat, this.localSearch.results[0].lng)) < 2000) {
            //Take the first result and add a base
            var result = this.localSearch.results[0];
			//$.data(window,'blueBase',result);
            this.bases[baseKey].init(new GLatLng(result.lat, result.lng), result.title);
            GEvent.addListener(this.bases[baseKey], "click", function(latlng) { this.openInfoWindowHtml(this.getTitle()); });
            this.map.addOverlay(this.bases[baseKey].marker);
            this.smallMap.addOverlay(this.bases[baseKey].smallMarker);

            //Setup next search
            this.localSearch.clearResults();
            this.localSearch.setCenterPoint(new GLatLng(this.map.getCenter().lat(), this.map.getCenter().lng() - .005));
    	} else {
			var me = this;
            //Otherwise call streetview to get a nearby street
            this.streetView.getNearestPanoramaLatLng(this.map.getCenter().addLng(0.006 * Math.random()),
            function(result) {
                if (result) {
                    me.bases[baseKey].init(result, baseKey);
                    GEvent.addListener(me.bases[baseKey].marker, "click", function(latlng) { this.openInfoWindowHtml("Church"); });
                    me.map.addOverlay(me.bases[baseKey].marker);
                    me.smallMap.addOverlay(me.bases[baseKey].smallMarker);
                }
                else {
                    me.bases[baseKey].init(me.map.getCenter().addLng(0.006 * Math.random()), baseKey);
                    GEvent.addListener(me.bases[baseKey], "click", function(latlng) { this.openInfoWindowHtml("Church"); });
                    me.map.addOverlay(me.bases[baseKey].marker);
                    me.smallMap.addOverlay(me.bases[baseKey].smallMarker);
                }
             });
        }
		
		if (baseKey == "church")
			this.executeLocalSearch("church");
		else this.onBasesLoaded();
	});
	
	this.localSearch.execute(this.bases[baseKey].constructor.localSearch);
}


HSEngine.prototype.onBasesLoaded = function(){
    //Clear the local search object for good
    this.localSearch = null;
    //Creat the first wave to start the game
    this.curWave = Wave.getWaveById(1, this);
}
